package com.csu.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.annotation.SaIgnore;
import com.csu.common.CommonResponse;
import com.csu.entity.News;
import com.csu.service.RichTextService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.UUID;


@Slf4j
/**
 * 与前端进行富文本相关的内容交互
 */
@RestController
public class RichTextController {
    @Autowired
    private RichTextService richTextService;
    /**
     * 富文本中的上传图片的下载与回显
     */
    @PostMapping("/file/picture")
    //@SaIgnore
    public CommonResponse<String> savePictureFile(@RequestParam("imgFile") MultipartFile imageFile) throws IOException {
        System.out.println("reached");
        String requestPath = richTextService.downloadFile(imageFile,0);
        if (requestPath.isEmpty())
            return CommonResponse.createForError("图片上传失败！");
        else
            return CommonResponse.createForSuccess("SUCCESS",requestPath);
    }

    /**
     * 富文本中的上传文件的下载与路径记录
     * 新闻通知的type为0
     */
    @PostMapping("/file/richtext")
    //@SaIgnore
    public CommonResponse<String> saveHtmlFile(@RequestParam("fileHtml") String fileHtml,
                                               @RequestParam("titleImg") String titleImg,
                                               @RequestParam("title") String title,
                                               @RequestParam("userId") int userId) throws  IOException{
        log.info("[访问接口:保存HTML文件]");
        //存储HTMl文件并且返回请求路径
        String requestPath = richTextService.saveHtmlFile(fileHtml);
        News news = new News();

        //设置news对象
        //设置标题图片
        if (titleImg.isEmpty())
            news.setTitleImg(null);
        else
            news.setTitleImg(titleImg);
        //设置其他
        news.setUserId(userId);
        news.setUserTitle(title);
        news.setNewsUrl(requestPath);
        // 设置时间
        LocalDateTime currentDateTime = LocalDateTime.now();
        news.setNewsDate(Timestamp.valueOf(currentDateTime));
        news.setType(0);

        System.out.println(news);
        log.info("[插入新闻通知]；内容为"+news);
        String msg = richTextService.insertNews(news);
        return CommonResponse.createForSuccess("SUCCESS",msg);
    }
}
